package com.cy.pj.sys.shiro;

import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {

    /*添加过滤条件*/
    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition =
                new DefaultShiroFilterChainDefinition();
        //配置/user/login/**开头的资源，可以匿名访问(不用登录就可以访问),
//其中 anon 为 shiro 框架指定的匿名过滤器
        chainDefinition.addPathDefinition("/user/login/**","anon");
//配置登出操作
        chainDefinition.addPathDefinition("/user/logout","logout");
//配置以/**开头的资源必须都要经过认证，
//其中 authc 为 shiro 框架指定的认证过滤器
        chainDefinition.addPathDefinition("/**", "authc");
        return chainDefinition;
    }


    /*添加 Realm 对象配置*/
    @Bean
    public Realm realm() {
        return new ShiroRealm();
    }



    @Bean
    public RememberMeManager rememberMeManager(){
        CookieRememberMeManager rememberMeManager=new CookieRememberMeManager();
        SimpleCookie cookie=new SimpleCookie("rememberMe");
        cookie.setMaxAge(7*24*60*60);//设置cookie的生命周期
        rememberMeManager.setCookie(cookie);
        rememberMeManager.setCipherKey(
                Base64.decode("WGjHie9R114WBoCm3TAZ0g=="));
        return rememberMeManager;
    }

    /*配置授权缓存管理器,默认应用的缓存是shiro框架内置的缓存对象
     * 缓存实现就是一个map
     *
     * */
    @Bean
    protected CacheManager shiroCacheManager() {
        return new MemoryConstrainedCacheManager();
    }


}
